package com.zjsd.sqeybusiness.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.zjsd.sqeybusiness.domain.Wechatconfig;
import com.zjsd.sqeybusiness.mapper.WechatconfigMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class WeChatAccessTokenUtil {

    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    private static final String GET_USER_OPENID = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s&next_openid=%s";
    public static String getAccessToken(WechatconfigMapper wechatconfigMapper) {
        Wechatconfig wechatconfig = wechatconfigMapper.selectWechatconfigById(1L);
        if (wechatconfig == null) {
            throw new CustomException("Wechatconfig not found");
        }

        // 检查access_token是否过期
        if (wechatconfig.getCssj() != null && wechatconfig.getCssj().after(new Date()) && StringUtils.isNotBlank(wechatconfig.getAccesstoken())) {
            return wechatconfig.getAccesstoken();
        }
        // 重新获取access_token
        String accessToken = fetchAccessTokenFromWeChat(wechatconfig.getAppid(), wechatconfig.getAppserect());
        System.out.println("重新获取access_token: " + accessToken);
        wechatconfig.setAccesstoken(accessToken);
        wechatconfig.setHqsj(new Date());
        wechatconfig.setCssj(new Date(System.currentTimeMillis() + 7200000)); // 有效期为2小时
        wechatconfig.setYxsj(7200000L);
        wechatconfigMapper.updateWechatconfig(wechatconfig);
        return accessToken;
    }

    private static String fetchAccessTokenFromWeChat(String appid, String secret) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(String.format(ACCESS_TOKEN_URL, appid, secret));
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, "UTF-8");
                System.out.println("获取access_token结果：" + result);
                JSONObject jsonObject = JSONObject.parseObject(result);
                return jsonObject.getString("access_token");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getAccessOpenId(String accessToken, String nextOpenId) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(String.format(GET_USER_OPENID, accessToken, nextOpenId));
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, "UTF-8");
                System.out.println("获取access_token结果：" + result);
                JSONObject jsonObject = JSONObject.parseObject(result);
                return jsonObject.getString("data");
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String accessToken = "91_Cgje3rq-N-5KuGhgYzjQwltuN61oSnyI2_pMUl3rVfCZIg6E1P8y56nRhBLcGnlGrPlisB9dBa770t6Lr1WVM3ExhAIrip9WNRDNmriJJhcz0yD1GUhkZ_ceqmYNTBcAHATZH";
        String nextOpenId = "";
        try {
            String result = getAccessOpenId(accessToken, nextOpenId);
            if(StringUtils.isNotEmpty(result)){
                JSONObject jsonObject = JSONObject.parseObject(result);
                if(jsonObject.containsKey("openid")){
                    JSONArray jsonArray = jsonObject.getJSONArray("openid");
                    List<String> list = new ArrayList<>();
                    for(int i = 0; i < jsonArray.size(); i++){
                        list.add(jsonArray.getString(i));
                        System.out.println("openid:"+jsonArray.getString(i));
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
